<?php


namespace App\Http\Services\System;


use App\Http\Models\Mysql\NnyyMenuTable;
use App\Http\Models\Mysql\NnyyRolePermission;
use App\Http\Models\Mysql\NnyyRoleTable;

class MenuService
{
    //获取树 all 获取所以树节点
    public function getTreeData($all = true)
    {
        $menuIds = [];
        if(!$all){
            //获取用户角色的路由权限
            $role = auth()->guard("api")->user()->role;
            $roleObj = (new NnyyRoleTable())->where("type", $role)->first();
            $rolePermissionObj = (new NnyyRolePermission())->where("role_id", $roleObj->id)->first();
            $menuIds = json_decode($rolePermissionObj->menu_ids, true);
        }
        $list = (new NnyyMenuTable())->where(['status' => 1])->orderBy("lie","asc")->get()->toArray();
        $nodeList = [];
        foreach ($list as $item){
            if(!empty($menuIds) && !in_array($item['id'], $menuIds)){
                continue;
            }
            $nodeList[$item['p_id']][] = $item;
        }
        $rootNodeList = $nodeList['ROOT'];
        $treeNodeList = [];
        foreach ($rootNodeList as $item){
            if(isset($nodeList[$item['id']])){
                $item['children'] = $nodeList[$item['id']];
                foreach ($item['children'] as &$childItem){
                    if(isset($nodeList[$childItem['id']])){
                        $childItem['children'] = $nodeList[$childItem['id']];
                    }
                }
                $treeNodeList[] = $item;
            }else{
                $treeNodeList[] = $item;
            }
        }
        return $treeNodeList;
    }

    //保存节点
    public function saveData($id, $data)
    {
        return (new NnyyMenuTable())->updateData($id, $data);
    }

    //新增节点
    public function addData($param)
    {
        $data = [
            'title' => $param['label'],
            'path' => $param['path'],
            'p_id' => $param['parent'],
            'lie' => time()
        ];
        $res = (new NnyyMenuTable())->createData($data);
        if($res['code'] === 0){
            $data['id'] = $res['id'];
            $res['data'] = $data;
        }
        return $res;
    }

    //删除节点
    public function delData($id)
    {
        return (new NnyyMenuTable())->deleteData($id);
    }
}
